package org.jsets.fastboot.util;

import java.io.IOException;
import java.util.List;

import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;
import org.springframework.core.io.ClassPathResource;
import cn.hutool.core.io.IoUtil;

public class IpRegionConverter {

	private static class SingleHolder {
		private static final IpRegionConverter INSTANCE = new IpRegionConverter();
	}

	public static IpRegionConverter getInstance() {
		return SingleHolder.INSTANCE;
	}

	private DbConfig config;
	private byte[] data;

	public IpRegionConverter() {
		try {
			ClassPathResource resource = new ClassPathResource("ip2region.db");
			this.data = IoUtil.readBytes(resource.getInputStream(), true);
			this.config = new DbConfig();
		} catch (Exception e) {
			// 忽略
		}
	}

	/**
	 * 获取地址
	 *   格式：
	 *   中国|0|北京|北京市|科技网
	 *	 中国|0|安徽省|合肥市|电信
	 * @param ip
	 * @return
	 */
	public String getRegion(String ip) {
		if (null == data) {
			throw new RuntimeException("请查看在ClassPath中是否存在数据库文件[ip2region.db]");
		}

		if (!Util.isIpAddress(ip)) {
			return "";
			//throw new IllegalArgumentException("参数不是有效的IP地址");
		}

		DbSearcher searcher = new DbSearcher(this.config, this.data);
		try {
			DataBlock dataBlock = searcher.memorySearch(ip);
			return dataBlock.getRegion();
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			searcher = null;
		}
	}
	
	public String getFormatted(String ip) {
		StringBuilder formatted = new StringBuilder();
		String region = this.getRegion(ip);
		
		if(region.contains("内网IP")) {
			return "内网";
		}
		
		List<String> ls = StringUtils.split(region,"\\|");
		if(ls.size()!=5) {
			return region;
		}
		
		if(!"中国".equals(ls.get(0))) {
			formatted.append(ls.get(0));
		}
		
		if(!"".equals(ls.get(2))) {
			if(formatted.length()>0) {
				formatted.append(" ");
			}
			formatted.append(ls.get(2));
		}
		
		if(!"".equals(ls.get(3))) {
			if(formatted.length()>0) {
				formatted.append(" ");
			}
			formatted.append(ls.get(3));
		}
		
		if(!"".equals(ls.get(4))) {
			if(formatted.length()>0) {
				formatted.append(" ");
			}
			formatted.append(ls.get(4));
		}
		
		ls = null;
		return formatted.toString();
	}

}